import React, { memo, useEffect, useRef } from 'react'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import classnames from 'classnames'

import { CategoryContent, CategoryItemImage, CategoryWrapper } from './style'
import { changeCurrentIdAction, getRadioCategories } from '../../store/actionCreators'
import { Carousel } from 'antd';

const PAGE_SIZE = 16;

export default memo(function HYRadioCategory () {
  const dispatch = useDispatch();
  const { categories, currentId } = useSelector(state => ({
    currentId: state.getIn(['djradio', 'currentId']),
    categories: state.getIn(['djradio', 'categories'])
  }), shallowEqual);

  const clength = categories && categories.length;
  const page = Math.ceil(clength / PAGE_SIZE) || 1;

  useEffect(() => {
    dispatch(getRadioCategories());
  }, [dispatch])

  const carouselRef = useRef();

  function getSize (index) {
    return index * PAGE_SIZE > clength ? index * PAGE_SIZE : clength;
  }

  return (
    <CategoryWrapper>
      <div className="arrow arrow-left" onClick={e => carouselRef.current.prev()}></div>
      <CategoryContent>
        <Carousel dots={{ className: 'dots' }} ref={carouselRef}>
          {
            Array(page).fill(0).map((_, index) => {
              return (
                <div className="category-page" key={index}>
                  {
                    categories.slice(index * PAGE_SIZE, getSize(index + 1)).map((item, indey) => {
                      return (
                        <div key={item.id}
                          onClick={e => dispatch(changeCurrentIdAction(item.id))}
                          className={classnames('category-item', { 'active': currentId === item.id })}
                        >
                          <CategoryItemImage className="image" imgUrl={item.picWebUrl}></CategoryItemImage>
                          <span>{item.name}</span>
                        </div>
                      )
                    })
                  }
                </div>
              )
            })
          }
        </Carousel>
      </CategoryContent>
      <div className="arrow arrow-right" onClick={e => carouselRef.current.next()}></div>
    </CategoryWrapper>
  )
})
